const api = require('../api/api')



function formatTime(date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}


/**
 * 封装微信的的request
 */
function request(url, data = {}, method = "GET") {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
        'AccessToken': wx.getStorageSync('access_token')
      },
      success: function (res) {
        // console.log("success");

        if (res.statusCode == 200) {

          if (res.data.errno == 401) {
            //需要登录后才可以操作

            let code = null;
            return wxLogin().then((res) => {
              code = res.code;
              return getUserInfo();
            }).then((userInfo) => {
              //登录远程服务器
              request(api.LoginUrl, {
                code: code,
                userInfo: userInfo
              }, 'POST').then(res => {
                if (res.errno === 0) {
                  //存储用户信息
                  wx.setStorageSync('userInfo', res.data.userInfo);
                  wx.setStorageSync('token', res.data.token);

                  resolve(res);
                } else {
                  reject(res);
                }
              }).catch((err) => {
                reject(err);
              });
            }).catch((err) => {
              reject(err);
            })
          } else {
            // console.log(res , wx.getStorageSync('access_token') );

            resolve(res.data);
          }
        } else {
          reject(res.errMsg);
        }

      },
      fail: function (err) {
        reject(err)
        console.log("failed")
      }
    })
  });
}

function get(url, data = {}) {
  return request(url, data, 'GET')
}

function post(url, data = {}) {
  return request(url, data, 'POST')
}

function wxLogin() {
  return new Promise((reslove, reject) => {
    wx.login({
      timeout: 10000,
      success: (result) => {
        console.log('login', result);
        reslove(result.code);
      },
      fail: (err) => {
        reject(err);
      }
    });
  })
}

function login(detail, app , callback ) {
  if (!detail) {
    return;
  }
  let {
    encryptedData,
    iv
  } = detail;
  let userInfo = app.globalData.userInfo;
  loading('正在登陆',true)
  wxLogin().then((code) => {
    // 请求后台接口
    post(api.LoginUrl, {
      code,
      encryptedData,
      iv,
      userInfo
    }).then((result) => {
      if (result.res == 1) {
        wx.hideLoading();
        console.log(result.data);
        app.globalData.access_token = result.data.access_token;

        // 登陆后缓存access_token
        wx.setStorage({
          key: 'access_token',
          data: result.data.access_token,
          success() {
            console.log('access_token save');
          }
        });
        if(callback){
          callback();
        }
      }
    })
  }).catch((err) => {
    toastErr(err.errMsg)
  })

}

function getUiAndLogin(detail , app , callback){
  // 未授权成功
  if( detail.errMsg.indexOf('fail')>-1 ){
    return;
  }
  app.globalData.userInfo = detail.userInfo
  wx.setStorageSync('userInfo', detail.userInfo);
  login(detail,app, callback ) ;
}

function toastErr(msg) {
  wx.showToast({
    title: msg,
    icon: 'none',
    duration: 1500,
    mask: true,
  });
}

// 提示
function toastSuccess(msg) {
  wx.showToast({
    title: msg,
    icon: 'success',
    duration: 1000,
    mask: true,
  });
}
// 显示loading    loading
function loading(title, infinite = true, duration) {
  if (infinite) { // 无限时loading
    wx.showLoading({
      title: title ? title : '加载中',
      mask: true
    })
    return;
  }
  wx.showToast({
    title: title ? title : '加载中',
    icon: 'loading',
    duration: duration || 20000, //默认和app.json设置的请求超时时间一致
    mask: true
  });
  if (duration) {
    setTimeout(() => {
      wx.hideToast();
    }, duration)
  }
}

// 隐藏loading
function hideLoading() {
  wx.hideToast();
}

/**
 * 校验手机号码是否合法
 * return  true或者false
 */
function checkPhone(phonenum) {
  var reg = /^(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
  var tag = true;
  if (phonenum == "") {
    tag = false;
  }
  if (!phonenum || phonenum.length != 11) {
    tag = false;
  } else if (!reg.test(phonenum)) {
    tag = false;
  }
  return tag;
}


// 微信支付
function wxPay(orderMsg  , sumMoney , start_time ) {
    wx.requestPayment({
      timeStamp: orderMsg.timeStamp,
      nonceStr: orderMsg.nonceStr,
      package: orderMsg.package,
      signType: orderMsg.signType,
      paySign: orderMsg.paySign,
      success: (result) => {
        console.log('支付完成', result);
        hideLoading()
        toastSuccess('支付成功')
        wx.redirectTo({
            url: `../pay_success/index?pay_money=${sumMoney}&reach_time=${start_time}`,
          });
      },
      fail: (err) => {
        if (err.errMsg.indexOf('cancel')) {
          toastErr('支付被取消')
        }
      }
    });
}
// 创建订单
function createOrder(data , sumMoney , start_time ) {
    loading('正在创建订单')
    post(api.CreateOrderUrl, data).then((orderMsg) => {
      if (orderMsg.res == 1) {
        wxPay(orderMsg.data , sumMoney , start_time )
      } else {
        showToast(orderMsg.msg)
      }
    })
}
/**
 * 获取某种格式当天日期
 *
 * @param {string} [link='-'] 默认为yyyy-mm-dd形式
 */
function today(link = '-') {
  var date = new Date();
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  return (year + link + month + link + strDate);
}

function ShareAppMessage(res,thatMeg){
  if (res.from === 'button') {
    // 来自页面内转发按钮
    console.log(res.target)
  }
  return {
    title: thatMeg.title ||"庐山西海瑶池湾度假山庄",
    path: thatMeg.path,
    imageUrl: thatMeg.imgUrl
  }
}

module.exports = {
  ShareAppMessage,//转发
  formatTime,
  formatNumber,
  request, // 请求
  get, // get请求
  post, // post请求
  login, // 登陆接口
  getUiAndLogin,  // 获取UserInfo并登录
  createOrder, // 创建订单并支付
  toastErr,
  toastSuccess,
  loading,
  hideLoading,
  checkPhone,
  today
}
